package com.gzy.demo1.controller;


import com.gzy.demo1.dto.R;
import com.gzy.demo1.model.Account;
import com.gzy.demo1.model.MyLog;
import com.gzy.demo1.resp.AccountRepository;
import com.gzy.demo1.resp.MyLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@CrossOrigin(origins = "http://localhost:9528", maxAge = 3600)
@RestController
@RequestMapping("/mylog")
public class MyLogController {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    MyLogRepository myLogRepository;

    @PostMapping
    R<?> add(@AuthenticationPrincipal UserDetails user,@RequestBody MyLog myLog){
        Account account = accountRepository.findAccountByUsername(user.getUsername());
        myLog.setUid(account.getId());
        myLog.setId(null);
        myLogRepository.save(myLog);
        return new R(null,R.Code.OK,"创建成功！");
    }

    @GetMapping
    R<List<MyLog>> index(@AuthenticationPrincipal UserDetails user){
        Account account = accountRepository.findAccountByUsername(user.getUsername());
        List<MyLog> all = myLogRepository.findAllByUid(account.getId());
        return new R<List<MyLog>>(all,R.Code.OK,"查询成功");
    }


    @DeleteMapping("/{id}")
    R<?> remove(@AuthenticationPrincipal UserDetails user,@PathVariable Long id){
        Account account = accountRepository.findAccountByUsername(user.getUsername());
        MyLog t = new MyLog();

        t.setId(id);
        t.setUid(account.getId());

        myLogRepository.delete(t);
        return new R(null,R.Code.OK,"删除成功！");
    }

    @PutMapping("/{id}")
    R<?> update(@AuthenticationPrincipal UserDetails user,@PathVariable Long id,@RequestBody MyLog myLog){
        Account account = accountRepository.findAccountByUsername(user.getUsername());


        Optional<MyLog> byId = myLogRepository.findById(id);

        if (byId.isEmpty()){
            return new R(null,R.Code.error,"不存在该数据");
        }

        MyLog myLog1 = byId.get();

        if (!account.getId().equals(byId.get().getUid())){
            return new R(null,R.Code.error,"不允许访问该数据");
        }

        myLog1.setContent(myLog.getContent());

        myLogRepository.save(myLog1);

        return new R(null,R.Code.OK,"修改成功！");
    }

}
